package cn.ymkj.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.ymkj.dto.LoginDto;
import cn.ymkj.pojo.User;
import cn.ymkj.service.UserService;
import cn.ymkj.utils.MyTokenUtil;
import cn.ymkj.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Api(tags = "登陆相关请求的接口")
@RestController
@RequestMapping("/login")
public class LoginController {

    @Resource
    private UserService userService;

    /**
     * 获取验证码
     */
    @ApiOperation("获取图形验证码的接口")
    @GetMapping("/getImageCode")
    public R getImageCode(HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(70, 34, 4, 10);
        String code = lineCaptcha.getCode();
        //生成一个key，对应这个验证码
        String key = UUID.randomUUID().toString();
        Map<String,Object> map = new HashMap<>();
        map.put("key",key);
        map.put("imgUrl",lineCaptcha.getImageBase64Data());
        return R.ok("获取验证码成功",map);
    }

    /**
     * 登录验证
     */
    @ApiOperation("登录验证接口")
    @PostMapping("/checkLogin")
    @ApiImplicitParam(name = "LoginDto", value = "登录请求参数对象", required = true, dataType ="LoginDto")
    public R checkLogin(@RequestBody LoginDto loginDto){
        //从redis取出对于的验证码进行比对
        if("code".equals(loginDto.getImageCode())){
            User user = userService.checkLogin(loginDto.getUsername(), loginDto.getPassword());
            if(user != null){
                //登录成功，把token发送到客户端，后续客户端的每次请求都要携带这个token
                Map<String,Object> map = new HashMap();
                String token = MyTokenUtil.sign(user); //获取token
                map.put("token", token);
                map.put("user",user);
                return R.ok("登录成功",map);
            }else{
                return R.no("账号或密码错误");
            }
        }else{
            return R.no("验证码错误");
        }
    }

    /**
     * 查看个人信息，肯定需要登录才能访问，表示请求的时候必须携带token，而且token不失效的情况下才可以访问
     */
    @ApiOperation("查看个人信息的接口")
    @GetMapping("/showInfo")
    @ApiImplicitParam(value = "用户编号",name = "userId",paramType = "query")
    public void showInfo(Integer userId){
        System.out.println("查看个人信息成功！！");
    }

}